import { Body, Controller, Get, Param, ParseIntPipe, Post, Req } from '@nestjs/common';
import { DeviceService } from './device.service';
import { UtilsService } from '@app/utils';
import { CacheService } from '@app/cache';
import { ConfigureService } from '@app/configure';


@Controller('device')
export class DeviceController {
    private devicePortChargingKeyReg:string
    constructor(
        private readonly service:DeviceService,
        private utils:UtilsService,
        private readonly cache:CacheService,
        private readonly config:ConfigureService,
    ){
        this.devicePortChargingKeyReg = config.get('devicePortChargingKeyReg')
    }

    

    @Get('info/:id')
    async info(@Param('id', ParseIntPipe) id:number, @Req() { userId }) {
        const device = await this.service.baseInfo(id)
        if(!device) return this.utils.failRes()

        if(device.private == 1) { //私人装
            const auth = await this.service.queryPrivateAuth(id, userId)
            if(!auth) return this.utils.failRes('未授权，不可使用')
            return this.utils.successRes({device})
        }else {
            let station:any = {}
            if(device.stationId > 0) {
                station = await this.service.station(device.stationId, device.chargeType)
            }
        
            return this.utils.successRes({
                device,
                ...station
            })
        }

        
    }

    @Post('queryChargingInfo')
    async queryChargingInfo(@Body() dto:Array<{id:string, port:string}>) {
        const res = await this.cache.client.mget(...dto.map(v => (this.devicePortChargingKeyReg.replace(/\?/, v.id).replace(/\?/, v.port))))
        return this.utils.successRes(res)
    }
}
